﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace ReseverUpdater
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //更新文件地址
        string[] arrayUrl = {
            "http://172.168.10.180:9016/version/AutoUpdater.dll",
            "http://172.168.10.180:9016/version/E3Setup.exe",
            "http://172.168.10.180:9016/version/AutoUpdater.config"
        };


        int i = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            //窗体隐藏
            //关闭进程中的E3程序
            Thread.Sleep(1000);
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName == "E3Setup")
                {
                    p.Kill();
                }
            }

            string str = "172.168.10.180";
            int Port = 9016;

            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IAsyncResult iar = socket.BeginConnect(str, Port, null, null);
                iar.AsyncWaitHandle.WaitOne(500);
                socket.EndConnect(iar);
                if (!socket.Connected)
                {
                    arrayUrl.SetValue("http://www.cqpds.com:9016/version/AutoUpdater.dll", 0);
                    arrayUrl.SetValue("http://www.cqpds.com:9016/version/E3Setup.exe", 1);
                    arrayUrl.SetValue("http://www.cqpds.com:9016/version/AutoUpdater.config", 2);
                }
                socket.Close();
            }
            catch
            {
                arrayUrl.SetValue("http://www.cqpds.com:9016/version/AutoUpdater.dll", 0);
                arrayUrl.SetValue("http://www.cqpds.com:9016/version/E3Setup.exe", 1);
                arrayUrl.SetValue("http://www.cqpds.com:9016/version/AutoUpdater.config", 2);
            }
            //循环下载
            //for (int i = 0; i < arrayUrl.Length; i++)
            //{

            //    using (WebClient client = new WebClient())
            //    {

            //        string URLAddress = arrayUrl[i];

            //        string receivePath = System.Environment.CurrentDirectory;

            //        client.DownloadFileCompleted += client_DownloadFileCompleted;

            //        client.DownloadFileAsync(new Uri(URLAddress), System.IO.Path.GetFileName(URLAddress));
            //        //client.DownloadFile(URLAddress, receivePath + System.IO.Path.GetFileName(URLAddress));             
            //    }
            //}
            //HTTPRequest循环下载
            try
            {
                for (int i = 0; i < arrayUrl.Length; i++)
                {
                    Uri downUri = new Uri(arrayUrl[i]);

                    int ix = arrayUrl[i].LastIndexOf("/");

                    //建立一个ＷＥＢ请求，返回HttpWebRequest对象           
                    HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(downUri);
                    //设置接收对象的范围为0-10000000字节。

                    hwr.AddRange(0, 10000000);

                    //流对象使用完后自动关闭
                    using (Stream stream = hwr.GetResponse().GetResponseStream())
                    {
                        //文件流，流信息读到文件流中，读完关闭@"D:\E3Setup"
                        using (FileStream fs = File.Create(Environment.CurrentDirectory + "\\" + arrayUrl[i].Substring(ix + 1, arrayUrl[i].Length - ix - 1)))
                        {
                            //建立字节组，并设置它的大小是多少字节
                            byte[] bytes = new byte[102400];
                            int n = 1;
                            while (n > 0)
                            {
                                //一次从流中读多少字节，并把值赋给Ｎ，当读完后，Ｎ为０,并退出循环
                                n = stream.Read(bytes, 0, 10240);
                                fs.Write(bytes, 0, n); //将指定字节的流信息写入文件流中
                            }
                        }
                    }
                }
                label1.Text = "E3更新程序关键组件更新完成，请重启E3程序";
                button1.Visible = true;
            }
            catch (Exception ex)
            {

                MessageBox.Show("下载过程中出现异常" + ": " + ex);
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            i++;
            if (i == arrayUrl.Length)
            {
                label1.Text = "E3更新程序关键组件更新完成，请重启E3程序";
                button1.Visible = true;
            }
        }
    
        public Dictionary<string, RemoteFile> ParseRemoteXml(string xml)
        {
            XmlDocument document = new XmlDocument();
            document.Load(xml);

            Dictionary<string, RemoteFile> list = new Dictionary<string, RemoteFile>();
            foreach (XmlNode node in document.DocumentElement.ChildNodes)
            {
                list.Add(node.Attributes["path"].Value, new RemoteFile(node));
            }

            return list;
        }
    }
}
